// pages/classic/classic.js
import {
  ClassicModel
} from '../../models/classic.js'
import {
  LikeModel
} from '../../models/like.js'

const classicModel = new ClassicModel()
const likeModel = new LikeModel()

Component({

  /**
   * 页面的初始数据
   */

  properties: {
    cid: Number,
    type: Number
  },

  data: {
    classic: {},
    latest: true,
    first: false,
    likeCount: 0,
    likeStatus: false
  },

  /**
   * 生命周期函数--监听页面加载
   * 回调地狱：回调嵌套过多；promise解决这个问题
   */
  attached: function () {
    const cid = this.properties.cid
    const type = this.properties.type
    //使用回调函数剥夺了return的能力，return返回的值来不了这个模块里
    if (!cid) {
      classicModel.getLatest((res) => {
        this.setData({
          classic: res,
          likeCount: res.fav_nums,
          likeStatus: res.like_status
        })
        // latestClassic/latestIndex  currentClassic/currentIndex 比较两个index是否相等就知道当前index是否是最新期刊
      })
    } else {
      classicModel.getById(cid, type, res => {
        this._getLikeStatus(res.id, res.type)
        this.setData({
          classic: res,
          latest: classicModel.isLatest(res.index),
          first: classicModel.isFirst(res.index)
        })
      })
    }
    //异步函数wx.request,   node.js中多为异步
    // wx.request({
    //   url: 'http://bl.7yue.pro/v1/classic/latest',
    //   header: {
    //     appkey: "hEXBAMR4CsGJ8kIy"
    //   },
    //   success:(res) => {//异步执行的成功后的回调函数
    //     console.log(this.data.test)
    //   }
    // })
  },

  methods: {
    onLike(event) {
      let behavior = event.detail.behavior
      likeModel.like(behavior, this.data.classic.id, this.data.classic.type)
    },
    onNext: function (event) {
      this._updateClassic('next')
    },
    onPrevious(event) {
      this._updateClassic('previous')
    },
    _updateClassic(nextOrPrevious) {
      let index = this.data.classic.index
      classicModel.getClassic(index, nextOrPrevious, (res) => {
        //因为有异步操作，所以不能直接更改res值，因此需要把喜欢这个功能的状态独立出来而不是放在res中
        this._getLikeStatus(res.id, res.type)
        // console.log(this.data.likeStatus)
        this.setData({
          classic: res,
          latest: classicModel.isLatest(res.index),
          first: classicModel.isFirst(res.index)
        })
      })
    },
    _getLikeStatus(artID, category) {
      likeModel.getClassicLikeStatus(artID, category, (res) => {
        //this.setData是异步函数
        this.setData({
          likeCount: res.fav_nums,
          likeStatus: res.like_status
        })
        // console.log(this.data.likeStatus)
      })
    }

  }

  /**
   * 生命周期函数--监听页面初次渲染完成
   */

})